package com.hks360.car_treasure.fragment;

import android.content.res.ColorStateList;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.hks360.car_treasure.R;
import com.hks360.car_treasure.activity.FindPassActivity;
import com.hks360.car_treasure.activity.MainActivity;
import com.hks360.car_treasure.common.AppConfig;
import com.hks360.car_treasure.common.Method;
import com.hks360.car_treasure.common.PrefKey;
import com.hks360.car_treasure.manager.CommonDataManager;
import com.hks360.car_treasure.model.Add.User;
import com.hks360.car_treasure.mvp.user.presenter.UserPresenter;
import com.hks360.car_treasure.mvp.user.presenter.UserPresenterImpl;
import com.hks360.car_treasure.mvp.user.view.UserView;
import com.hks360.car_treasure.socket.CommunicationManager;
import com.hks360.library.util.CommonUtil;
import com.hks360.library.util.PrefUtil;
import com.hks360.library.util.UIUtil;

/**
 * 用户登录
 */
public class LoginFragment extends BaseFragment implements UserView {
    private TextView mLoginTv;
    private EditText mPhoneEt;
    private EditText mPasswordEt;
    private CheckBox mPasswordCb;
    private CheckBox mAutoCb;
    private TextView mFindPassTv;

    private UserPresenter mUserPresenter;

    @Override
    public void initView() {
        initDialog(R.string.loading_login);
        setupView();
        initFindpassText();
        initData();
        addListener();
    }

    @Override
    public void setupView() {
        mLoginTv = UIUtil.findViewById(mRootView, R.id.login_tv);
        mPhoneEt = UIUtil.findViewById(mRootView, R.id.login_phone_et);
        mPasswordEt = UIUtil.findViewById(mRootView, R.id.login_pass_et);
        mPasswordCb = UIUtil.findViewById(mRootView, R.id.login_pass_cb);
        mAutoCb = UIUtil.findViewById(mRootView, R.id.login_auto_cb);
        mFindPassTv = UIUtil.findViewById(mRootView, R.id.login_findpass_tv);
    }

    @Override
    public void initData() {
        mUserPresenter = new UserPresenterImpl(getContext(),this);

        if (PrefUtil.getBoolean(getActivity(), PrefKey.LOGIN_SAVE_PASS, false)) {
            mPasswordCb.setChecked(true);
            mPhoneEt.setText(PrefUtil.getString(getContext(), PrefKey.LOGIN_PHONE, null));
            mPasswordEt.setText(PrefUtil.getString(getContext(), PrefKey.LOGIN_PASSWORD, null));
        }
    }

    public void addListener() {
        mLoginTv.setOnClickListener(this);
    }

    private boolean isInputError() {
        if (CommonUtil.isEmptyEt(mPhoneEt) || CommonUtil.isEmptyEt(mPasswordEt)) {
            CommonUtil.showToast(getContext(), "请您将信息填写完整后再按进行登录");
            return true;
        }
        if (mPasswordEt.getText().toString().length() > 20 || mPasswordEt.getText().toString().length() < 6) {
            CommonUtil.showToast(getContext(), "请您按提示输入密码位数");
            return true;
        }
        return false;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_login, null);
        initView();
        return mRootView;
    }

    private void initFindpassText() {
        SpannableString sp = new SpannableString(getResources().getString(R.string.forget_pass));
        ColorStateList csllink = getResources().getColorStateList(R.color.app_blue);
        ColorStateList csl = getResources().getColorStateList(R.color.app_blue);
        sp.setSpan(new TextAppearanceSpan("monospace", Typeface.NORMAL, 30, csl, csllink), 0,
                getResources().getString(R.string.forget_pass).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        sp.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                CommonUtil.openActivity(getContext(), FindPassActivity.class);
            }
        }, 0, getResources().getString(R.string.forget_pass).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mFindPassTv.setText(sp);
        mFindPassTv.setMovementMethod(LinkMovementMethod.getInstance());
    }

    @Override
    public void viewClick(View v) {
        switch (v.getId()) {
            case R.id.login_tv:
                if (!isInputError()) {
                    mUserPresenter.login(R.id.login_tv);
                }
                break;
        }
    }

    @Override
    public void showLoading() {
        mDialog.show();
    }

    @Override
    public void hideLoading() {
        mDialog.dismiss();
    }

    @Override
    public String getMobile() {
        return mPhoneEt.getText().toString().trim();
    }

    @Override
    public String getCode() {
        return null;
    }

    @Override
    public String getPassword() {
        return mPasswordEt.getText().toString().trim();
    }

    @Override
    public void loginSuccess(User user) {
        Method.setI(PrefUtil.getInt(getContext(),PrefKey.COUNT,0));
        AppConfig.user = user;
        if(!PrefUtil.getString(getContext(),PrefKey.LOGIN_PHONE,"").equals(mPhoneEt.getText().toString().trim())){
            PrefUtil.putInt(getContext(),PrefKey.COUNT,0);
            Method.setI(PrefUtil.getInt(getContext(),PrefKey.COUNT,0));
        }
        PrefUtil.putString(getContext(), PrefKey.LOGIN_PHONE, mPhoneEt.getText().toString().trim());
        PrefUtil.putString(getContext(),PrefKey.TRUENAME,user.getTruename().trim());
        PrefUtil.putString(getContext(), PrefKey.EMAIL, user.getEmail().trim());
        if (mPasswordCb.isChecked()) {
            PrefUtil.putBoolean(getContext(), PrefKey.LOGIN_SAVE_PASS, true);
            PrefUtil.putString(getContext(), PrefKey.LOGIN_PASSWORD, getPassword());
        } else {
            PrefUtil.removeKey(getContext(), PrefKey.LOGIN_SAVE_PASS);
        }
        if (mAutoCb.isChecked()) {
            PrefUtil.putBoolean(getContext(), PrefKey.LOGIN_IS_AUTO, true);
        } else {
            PrefUtil.removeKey(getContext(), PrefKey.LOGIN_IS_AUTO);
        }
        CommonUtil.openActivity(getContext(), MainActivity.class);
        if (AppConfig.user.getTboxinfo().size() != 0) {
            while (AppConfig.mComManager == null){
                try{
                    if(AppConfig.mComManager == null){
                        AppConfig.mComManager = new CommunicationManager(getContext());
                        setServer();
                    }
                }catch (Exception e){

                }

            }
            PrefUtil.putString(getContext(), PrefKey.TBOX_ID, Method.getTboxId());
            AppConfig.mComManager.loading(Method.getTboxId(), PrefUtil.getString(getContext(), PrefKey.LOGIN_PHONE, ""), PrefUtil.getString(getContext(), PrefKey.LOGIN_PASSWORD, ""));
            AppConfig.mComManager.startHeartBeat();
        }else if(AppConfig.mComManager == null){
            AppConfig.mComManager = new CommunicationManager(getContext());
        }
        getActivity().finish();
    }
    private void setServer() {
        AppConfig.mComManager.setADDRESS(Method.getServer().split(":")[0].trim());
        AppConfig.mComManager.setPOT(Integer.valueOf(Method.getServer().split(":")[1].trim()));
        Log.e("RWQ111", Method.getServer().split(":")[0]);
        Log.e("RWQ111", Method.getServer().split(":")[1]);
    }


    @Override
    public void showToastMsg(String msg) {
        if(msg != null){
            CommonUtil.showToast(getContext(),msg);
        }
    }

    @Override
    public void sendCheckCodeSuccess() {

    }

    @Override
    public void findPasswordSuccess() {

    }

    @Override
    public void clearView() {
        mPhoneEt.setText(null);
        mPasswordEt.setText(null);
    }

    @Override
    public void sendCheckCodeFailed() {

    }

}
